package com.kfirszt.elearning.persistence.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.kfirszt.elearning.dictionary.Province;
import com.kfirszt.elearning.persistence.model.City;

@Repository("cityDAO")
public class CityDAOImpl extends GenericDAOImpl<City, Long> implements CityDAO {

	@Override
	public Class<City> getEntityClass() {
		return City.class;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public City findByNameAndProvinceOrCreate(String name, Province province) {
		City result;
		DetachedCriteria criteria = DetachedCriteria.forClass(City.class);
		criteria
			.add(Restrictions.eq("name", name))
			.add(Restrictions.eq("province", province));
		List resultList = hibernateTemplate.findByCriteria(criteria);
		if(resultList != null && resultList.isEmpty()==false)
			result = (City) resultList.get(0);
		else{
			result = new City();
			result.setName(name);
			result.setProvince(province);
			saveOrUpdate(result);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<City> findByName(String query) {
		DetachedCriteria criteria = DetachedCriteria.forClass(City.class);
		criteria.add(Restrictions.like("name", query, MatchMode.START));
		return hibernateTemplate.findByCriteria(criteria, 0, 10);
	}


}
